<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      width="30%"
      :title="getTitle"
      @ok="handleSubmit"
      destroyOnClose
    >
      <BasicForm @register="registerForm">
        <template #schoolSlot="{ model, field }">
          <div class="school">
            <Input placeholder="输入中英文名称，用逗号隔开" v-model:value="model[field]" />
            <a-button type="primary" class="btn" @click="handleAddSchool"> 添加学校 </a-button>
          </div>
        </template>
        <template #communitySlot="{ model, field }">
          <div class="school">
            <Input placeholder="输入中英文名称，用逗号隔开" v-model:value="model[field]" />
            <a-button type="primary" class="btn" @click="handleAddCommunity"> 添加社区 </a-button>
          </div>
        </template>
        <template #schoolDeleteSlot="{ model, field }">
          <div class="school">
            <Input placeholder="输入中英文名称，用逗号隔开" v-model:value="model[field]" />
            <a-button danger class="btn" @click="handleDeleteSchool(field)"> 删除学校 </a-button>
          </div>
        </template>
        <template #communityDeleteSlot="{ model, field }">
          <div class="school">
            <Input placeholder="输入中英文名称，用逗号隔开" v-model:value="model[field]" />
            <a-button danger class="btn" @click="handleDeleteCommunity(field)"> 删除社区 </a-button>
          </div>
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { buildingFormSchema } from './cityManage.data';
  import { defineComponent, ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Input } from 'ant-design-vue';

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      Input,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const getTitle = ref('');
      const isUpdate = ref(false);
      const countSchool = ref(0);
      const schoolArr = ref<any[]>([]);
      const countCommunity = ref(0);
      const communityArr = ref<any[]>([]);

      // 表单
      const [
        registerForm,
        { setFieldsValue, resetFields, validate, appendSchemaByField, removeSchemaByFiled },
      ] = useForm({
        labelWidth: 140,
        schemas: buildingFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      // 模态框
      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = data.isUpdate;
        if (data.isUpdate) {
          getTitle.value = '编辑城市';
          setFieldsValue({
            ...data.record,
          });
        } else {
          getTitle.value = '新增城市';
        }
      });

      const handleSubmit = async () => {
        try {
          // 表单校验
          const values = await validate();
          // 开启确定按钮的加载状态
          setModalProps({ confirmLoading: true });
          const { createMessage } = useMessage();
          values.schoolType = schoolArr.value;
          values.communityType = communityArr.value;
          console.log(values);

          if (isUpdate.value) {
            // 编辑
            createMessage.success('编辑成功');
          } else {
            // 新增
            createMessage.success('新增成功');
          }
          emit('success');
          closeModal();
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };

      // 添加学校
      const handleAddSchool = () => {
        appendSchemaByField(
          {
            field: 'newSchool-' + countSchool.value,
            label: '学校',
            component: 'Input',
            slot: 'schoolDeleteSlot',
          },
          'school'
        );
        schoolArr.value.push({
          field: 'newSchool-' + countSchool.value,
        });
        countSchool.value++;
        console.log(schoolArr.value);
      };

      // 删除学校
      const handleDeleteSchool = (field) => {
        const index = field.split('-')[1];
        removeSchemaByFiled('newSchool-' + index);
        let Index = -1;
        schoolArr.value.forEach((item: any, i) => {
          if (item.field.indexOf(index) !== -1) {
            Index = i;
          }
        });
        schoolArr.value.splice(Index, 1);
        countSchool.value--;
        console.log(schoolArr.value);
      };

      // 添加社区
      const handleAddCommunity = () => {
        appendSchemaByField(
          {
            field: 'newCommunity-' + countCommunity.value,
            label: '社区',
            component: 'Input',
            slot: 'communityDeleteSlot',
          },
          'community'
        );
        communityArr.value.push({
          field: 'newCommunity-' + countCommunity.value,
        });
        countCommunity.value++;
        console.log(communityArr.value);
      };

      // 删除社区
      const handleDeleteCommunity = (field) => {
        const index = field.split('-')[1];
        removeSchemaByFiled('newCommunity-' + index);
        let Index = -1;
        communityArr.value.forEach((item: any, i) => {
          if (item.field.indexOf(index) !== -1) {
            Index = i;
          }
        });
        communityArr.value.splice(Index, 1);
        countCommunity.value--;
        console.log(communityArr.value);
      };

      return {
        getTitle,
        registerForm,
        registerModal,
        handleSubmit,
        handleAddSchool,
        handleAddCommunity,
        handleDeleteSchool,
        handleDeleteCommunity,
      };
    },
  });
</script>

<style scoped lang="less">
  .school {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn {
      margin-left: 10px;
    }
  }
</style>
